package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {

    private static  final  String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";
    private static final String SIGN_ON_FORM = "/WEB-INF/jsp/account/signon.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        * 获取传过来的值
        * 从session获取cart
        * 第一次可能为null 补充判断
        * 参考先前代码可知
         * 判断如果购物车有这个商品 商品数量改变
         * 如果没有这个商品 addItem
         * 最后将商品放到session里面
         * 页面跳转
        * */
        String workingItemId = req.getParameter("workingItemId");
        HttpSession session = req.getSession();
        CartItem cart = (CartItem) session.getAttribute("cart");
        Account account = (Account) session.getAttribute("loginAccount");
        CartService cartService = new CartService();

        if(account == null){
            resp.sendRedirect("cartForm");
        }

        if(cart == null){
            cart = new CartItem();
        }

        if (cartService.isInCart(account.getUsername(),workingItemId)) {
            cartService.incrementQuantity(account.getUsername(),workingItemId);
        } else {
            CatalogService catalogService = new CatalogService();
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cartService.addItem(account.getUsername(),item);
        }

        session.setAttribute("cart",cart);
        resp.sendRedirect("cartForm");
        //req.getRequestDispatcher(CART_FORM).forward(req,resp);
    }
}
